using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
using YouTrackSharp.Tests.Infrastructure;

// ReSharper disable once CheckNamespace
namespace YouTrackSharp.Tests.Integration.Issues
{
    public partial class IssuesServiceTests
    {
        public class DownloadAttachment
        {
            [Fact]
            public async Task Valid_Connection_Gets_Attachments_For_Issue()
            {
                // Arrange
                var connection = Connections.Demo1Token;
                using (var temporaryIssueContext = await TemporaryIssueContext.Create(connection, GetType()))
                {
                    var service = connection.CreateIssuesService();
                    
                    using (var attachmentStream = await TestUtilities.GenerateAttachmentStream("Generated by unit test."))
                    {
                        await service.AttachFileToIssue(temporaryIssueContext.Issue.Id, "file1.txt", attachmentStream);
                    }
                
                    var attachments = await service.GetAttachmentsForIssue(temporaryIssueContext.Issue.Id);
                
                    // Act & Assert
                    using (var streamReader = new StreamReader(await service.DownloadAttachment(attachments.First().Url)))
                    {
                        var data = await streamReader.ReadToEndAsync();
                    
                        Assert.Equal("Generated by unit test.", data);
                    }

                    await temporaryIssueContext.Destroy();
                }
            }
        }
    }
}